package com.zhang.zhangapp.view.shop;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhang.zhangapp.MainActivity;
import com.zhang.zhangapp.PayResult;
import com.zhang.zhangapp.R;
import com.zhang.zhangapp.application.MApplication;
import com.zhang.zhangapp.base.Constant;
import com.zhang.zhangapp.base.http.MCallback;
import com.zhang.zhangapp.bean.shop.Ticket;
import com.zhang.zhangapp.bean.user.Recharge;
import com.zhang.zhangapp.http.CommonHttp;
import com.zhang.zhangapp.utils.ActivityManager;
import com.zhang.zhangapp.utils.T;
import com.zhang.zhangapp.view.BaseAppCompatActivityActivity;
import com.zhang.zhangapp.wxapi.WXPayEntryActivity;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 罗肖 on 2018/4/19.
 */

@ContentView(R.layout.activity_buy_coupon)
public class BuyCouponActivity extends BaseAppCompatActivityActivity {
    private final static int SDK_PAY_FLAG = 10000;
    @ViewInject(R.id.action_bar_title)
    TextView titleText;
    @ViewInject(R.id.coupon_name)
    TextView nameText;
    @ViewInject(R.id.coupon_price)
    TextView priceText;
    @ViewInject(R.id.delete_count)
    ImageView deleteCountImg;
    @ViewInject(R.id.add_count)
    ImageView addCountImg;
    @ViewInject(R.id.coupon_count)
    TextView couponCountText;
    @ViewInject(R.id.coupon_sum_amount)
    TextView sumAmountText;
    @ViewInject(R.id.mine_account_pay)
    TextView mineAccountPayText;//余额支付
    @ViewInject(R.id.mine_account_amount)
    TextView mineAccountAmountText;//我的余额
    @ViewInject(R.id.wx_pay)
    TextView wxPayText;//微信支付
    @ViewInject(R.id.ali_pay)
    TextView aliPayText;//支付宝支付
    @ViewInject(R.id.mine_account_pay_layout)
    RelativeLayout mineAccountAmountlayout;
    @ViewInject(R.id.wx_need_pay)
    TextView wxNeedPayText;
    @ViewInject(R.id.ali_need_pay)
    TextView aliNeedPayText;
    //1:余额,2:支付宝(或支付宝+余额)3:微信(或微信+余额)4:银联(或银联+余额)'
    String payMethod = "3";

    BigDecimal sumAmount = new BigDecimal(0);
    BigDecimal otherNeedPay = new BigDecimal(0);
    private int count = 1;

    private Ticket ticket;
    private String shopCode;


    TextChangeWatch textChangeWatch = new TextChangeWatch();
    private IWXAPI iwxapi;

    Map<String, String> params = new HashMap<>();

    private LocalBroadcastManager localBroadcastManager;
    private PayReciver payReciver;
    private IntentFilter intentFilter;
    MCallback payCallback = new MCallback() {
        @Override
        public void onSuccess(String data) {//和充值返回的值一样
            try {
                JSONObject jsonObject = new JSONObject(data);
                if (params.get("payMethod").equals("3")) {
                    String transNo = jsonObject.getString("transNo");
                    JSONObject reqStr = jsonObject.getJSONObject("reqStr");
                    sendPayRequest(reqStr, transNo);
                }else {
                    String transNo = jsonObject.getString("transNo");
                    String reqStr = jsonObject.getString("reqStr");
                    aliPay(reqStr);
                }
            } catch (Exception e) {

            }
        }

        @Override
        public void onSuccess(String message, String code) {

        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {

        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {
            dismisionDalog();
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        ticket = getIntent().getParcelableExtra("ticket");
        shopCode = getIntent().getStringExtra("shopCode");
        titleText.setText(ticket.getDescr());
        nameText.setText(ticket.getDescr());
        priceText.setText(ticket.getFactval() + "元");
        couponCountText.addTextChangedListener(textChangeWatch);
        priceText.addTextChangedListener(textChangeWatch);
        mineAccountAmountlayout.setVisibility(View.GONE);
        wxNeedPayText.setVisibility(View.GONE);
        aliNeedPayText.setVisibility(View.GONE);
        initWxSdk();
        intLocalBroadcast();
    }

    private void initWxSdk() {
        iwxapi = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID, false);
        iwxapi.registerApp(Constant.WX_APP_ID);
    }

    private void intLocalBroadcast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        intentFilter = new IntentFilter(WXPayEntryActivity.PAY_SUCCESS);
        payReciver = new PayReciver();
        localBroadcastManager.registerReceiver(payReciver, intentFilter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(payReciver);
    }

    @Event(type = View.OnClickListener.class, value = {R.id.action_bar_left_image, R.id.add_count, R.id.delete_count, R.id.mine_account_pay,
            R.id.wx_pay, R.id.ali_pay, R.id.pay_order_sure})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.action_bar_left_image:
                this.finish();
                break;
            case R.id.pay_order_sure:
                pay();
                break;
            case R.id.add_count:
                if (count < 99) {
                    count++;
                    couponCountText.setText(count + "");
                }
                break;
            case R.id.delete_count:
                if (count > 1) {
                    count--;
                    couponCountText.setText(count + "");
                }
                break;
            case R.id.mine_account_pay:
                payMethod = "1";
                selectPayMethod(view);
                break;
            case R.id.wx_pay:
                payMethod = "3";
                selectPayMethod(view);
                break;
            case R.id.ali_pay:
                payMethod = "2";
                selectPayMethod(view);
                break;
        }
    }

    private void selectPayMethod(View view) {
        wxPayText.setSelected(false);
        aliPayText.setSelected(false);
        mineAccountPayText.setSelected(false);
        view.setSelected(true);
    }

    private void pay() {
        params.put("shopCode", shopCode);
        params.put("memberId", MApplication.getInstance().getUser().getMemberId());
        params.put("realAmount", sumAmount.doubleValue() + "");
        params.put("ticketId", ticket.getShopticketId() + "");
        params.put("payMethod", payMethod);
        params.put("count", count + "");
        if (showLoadingDialog()) {
            CommonHttp.commonHttp("hzg/pay/buyTicket", params, payCallback);
        }
    }

    class TextChangeWatch implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            BigDecimal bdprice = new BigDecimal(ticket.getFactval());
            sumAmount = bdprice.multiply(new BigDecimal(count));

            String sum = sumAmount.toString();
            String preString = "(共" + count + "张)";
            SpannableString spannableString = new SpannableString(preString + sum + "元");
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.BLACK);
            spannableString.setSpan(colorSpan, 0, preString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            sumAmountText.setText(spannableString);
        }
    }

    /**
     * 调用微信支付
     */
    public void sendPayRequest(JSONObject object, String transaction) {
        try {
            PayReq req = new PayReq();
            req.appId = object.getString("appid");
            req.partnerId = object.getString("partnerid");
            //预支付订单
            req.prepayId = object.getString("prepayid");
            req.nonceStr = object.getString("noncestr");
            req.timeStamp = object.getString("timestamp");
            req.packageValue = object.getString("package");
            req.sign = object.getString("sign");
            req.transaction = transaction;
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            //3.调用微信支付sdk支付方法
            iwxapi.sendReq(req);
        } catch (Exception e) {
        }
    }

    private void aliPay(final String payInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(BuyCouponActivity.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

// 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if ("9000".equals(resultStatus)) {
                        Toast.makeText(BuyCouponActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        ((MainActivity) ActivityManager.getActivityManager().getActivty(MainActivity.class)).updateUserInfo();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if ("8000".equals(resultStatus)) {
                            Toast.makeText(BuyCouponActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(BuyCouponActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };

    class PayReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            BuyCouponActivity.this.finish();
            ActivityManager.getActivityManager().finishActivity(WXPayEntryActivity.class);
        }
    }
}
